﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using CoyoEden.Models;
using CoyoEden.Web.Data;
using CoyoEden.Web;
using CoyoEden.Web.Controls;
using Vivasky.Core.Infrastructure;

namespace CoyoEden.Web.Controller
{
	/// <summary>
	/// BLFacade for category mobile object.
	/// </summary>
	public class CategoryController: ControllerBase
	{
		/// <summary>
		/// select a single record
		/// </summary>
		public static Category Single(Dictionary<string,string> Params,out FeedbackData msg){
			msg = new FeedbackData();
			var user = Params["user"];
			var id = Convert.ToInt32(Params["id"]);
			Category tempCategory = null;
			try
			{
				if (id < 0)
				{
					tempCategory = new Category();
				}
				else
				{
					tempCategory = Category.GetCategory(id);
					if (tempCategory == null) {
						msg.Body = string.Format("<h3>无法获取此分类(编号:{0})的信息.</h3>", id);
					}
				}
			}
			catch (Exception ex) {
				ResolveException(ex,out msg);
			}
			return tempCategory;
		}
		public static void Update(List<NameValuePair<string, string>> Params,out FeedbackData msg)
		{
			msg = new FeedbackData();
			try
			{
				//need validate user?
				var user = Params.Find(item => item.name == "user");

				var id = Convert.ToInt32(Params.Find(item => item.name == "CategoryId").value);
				Category category = null;
				if (id <= 0)
				{
					category = new Category();
				}
				else
				{
					category = Category.Categories.Find(c => c.Id == id);
				}
				category.Title = Params.Find(item => item.name == "CategoryTitle").value;
				category.Description = Params.Find(item => item.name == "CategoryDesc").value;
				category.Slug = Params.Find(item => item.name == "CategorySlug").value;
				category.Icon = Params.Find(item => item.name == "CategoryIcon").value;//Absolute image url
				category.Icon = Utils.ConvertToRelative(category.Icon,true);//we need to save the app relative url to our database
				if (string.IsNullOrEmpty(category.Icon))
				{
					category.Icon = Category.NoIcon;
				}
				category.Parent = Convert.ToInt16(Params.Find(item => item.name == "CategoryParent").value);
        category.DisplayOrder = Convert.ToInt16(Params.Find(item => item.name == "CategoryDisplayOrder").value);
				category.Save();
			}
			catch (Exception ex)
			{
				ResolveException(ex, out msg);
			}
		}
		public static void Delete(Dictionary<string, string> Params,out FeedbackData msg)
		{
			msg = new FeedbackData();
			try
			{
				var keys = Params["keys"];
				var user = Params["user"];
				List<string> categoryIDs = keys.Split('|').ToList();
				//delete categories
				categoryIDs.ForEach(c =>
				{
					Category cat = Category.GetCategory(Convert.ToInt32(c));
					Post.Posts.ForEach(post =>
					{
						if (post.Categories.Contains(cat))
						{
							post.Categories.Remove(cat);
						}
					});
					cat.Delete();
					cat.Save();
				});
			}
			catch (Exception ex)
			{
				ResolveException(ex, out msg);
			}
		}
		public static void SelectCategories(Dictionary<string,string> Params,out FeedbackData msg) {
			msg = new FeedbackData();
			var currentPage = Convert.ToInt32(Params["CPage"]);
			var rowPerPage = Convert.ToInt32(Params["RPPage"]);
			var fatherID = Convert.ToInt32(Params["FatherID"]);
			var itemViewPath = Params["ViewPath"];

			var allItems = new List<Category>();
			if (fatherID == -1)
			{
				allItems = Category.TopCategories;
			}
			else {
				allItems = Category.GetChildren(Category.GetCategory(fatherID));
			}
			//do paging
			SimplePager pager = new SimplePager();
			List<Category> items = null;
			if (allItems != null && allItems.Count > 0)
			{
				pager.PagedList<Category>(allItems, rowPerPage, currentPage, out items);
				//Return first record's id!!.For the purpose of locating the latest record
				msg.Context.Add("TopItemID", items[0].Id);
			}
			else
			{
				pager.CurrentPage = currentPage;
				pager.RowPerPage = rowPerPage;
				pager.RowTotal = 0;
				pager.PageTotal = 0;
				pager.Tip = "没有任何记录可以显示";
			}


			//Load Page view
			ViewManager<SimplePagerViewBase> viewObj = new ViewManager<SimplePagerViewBase>("~/Views/SimplePager.ascx");
			viewObj.Control.Pager = pager;
			msg.Context.Add("PagerHtml", viewObj.Render());

			//Load ITEM view
			ViewManager<CategoryViewBase> itemView = new ViewManager<CategoryViewBase>(itemViewPath);
			itemView.Control.CategoriesShow = items;

			msg.Context.Add("CategoryListHtml", itemView.Render());

			msg.Context.Add("Pager", pager);
		}
	}
}
